package com.zj.album.graphy.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.zj.album.R;
import com.zj.album.graphy.GraphUtils;
import com.zj.album.graphy.PhotoFileHelper;
import com.zj.album.graphy.PhotographHelper;
import com.zj.album.graphy.adapter.PhotoGraphAdapter;
import com.zj.album.graphy.module.PhotoFileInfo;
import com.zj.album.graphy.module.PhotoInfo;
import com.zj.album.graphy.views.ChooseFilePop;
import com.zj.album.graphy.views.PhotoSelectedView;
import com.zj.album.interfaces.PhotoEvent;
import com.zj.album.services.Constancs;
import com.zj.album.utils.DisplayUtils;
import com.zj.album.utils.ToastUtils;

import java.lang.ref.WeakReference;
import java.util.List;

import static com.zj.album.services.Constancs.helperEvenErroCode;
import static com.zj.album.services.Constancs.helperEventCode;
import static com.zj.album.services.Constancs.helperEventCode_SelectedChange;

/**
 * Created by zhaojie on 2017/10/18.
 * <p>
 * the Intent data:
 *
 * @use photoSelectedComplete :when you photo_select completed,you can use this code to notify getData on your activityResult;
 * @use max :the max num you can selected;
 * @use cacheNameCode :the cache name to save for this operate,as a file;
 * <p>
 * <example>
 * <p>
 * var intent = Intent(this, PhotoGraphActivity::class.java);
 * intent.putExtra("photoSelectedComplete", "")
 * intent.putExtra("max", "")
 * intent.putExtra("cacheNameCode", "")
 * startActivity(intent)
 * @see: to get data:
 */

public class PhotoGraphActivity extends AppCompatActivity {

    private int maxPhotoSize = 0;
    private String cacheNameCode = "";
    private boolean hasEventData = false;
    private WeakReference<Context> context;

    private RecyclerView rvPhoto;
    private TextView tvFile, tvPreview, tvTitle, tvRight;
    private ImageView ivLeft;
    private PhotoGraphAdapter adapter;
    private GraphUtils graphUtils;
    private ChooseFilePop chooseFilePop;
    private FrameLayout flMenu;
    private PhotoEvent event;

    private boolean isSaveChooseWhenExit = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photograph);
        getBundleData();
        this.context = new WeakReference<Context>(this);
        synchronized (this) {
            initView();
            initData();
            initListener();
        }
    }

    private void getBundleData() {
        Bundle bundle = getIntent().getExtras();
        maxPhotoSize = bundle.getInt("max");
        cacheNameCode = bundle.getString("cacheNameCode");
    }

    private void initView() {
        rvPhoto = findViewById(R.id.photo_rv);
        tvFile = findViewById(R.id.photo_tvFile);
        tvPreview = findViewById(R.id.photo_tvCompleted);
        ivLeft = findViewById(R.id.photo_ivLeft);
        tvTitle = findViewById(R.id.photo_tvTitle);
        tvRight = findViewById(R.id.photo_tvRight);
        flMenu = findViewById(R.id.photo_flMenu);
        tvTitle.setText("相册选择");
        adapter = new PhotoGraphAdapter(new PhotoSelectedView.ChangeListener() {
            @Override
            public void onSelectChange(int position, boolean isSelected, String uri) {
                PhotographHelper.getHelper().onSelectedChanged(isSelected, uri, cacheNameCode, event);
                for (int i : PhotographHelper.getHelper().getRankModules()) {
                    if (i != position) adapter.notifyItemChanged(i);
                }
                adapter.notifyItemChanged(position);
            }

            @Override
            public boolean canSelected(int curNum) {
                return curNum < maxPhotoSize;
            }

            @Override
            public void onFailedSelected() {
                ToastUtils.show(getApplicationContext(), "最多只能选择" + maxPhotoSize + "张");
            }

            @Override
            public void onImgClick(boolean isSelected, String uri) {
                //打开所有图片预览
                startPreviewActivity(isSelected, true, uri);
            }

            @Override
            public int getCurRank(String uri) {
                return PhotographHelper.getHelper().isContainInSelected(cacheNameCode, uri)[1];
            }
        });
        rvPhoto.setAdapter(adapter);
        ((SimpleItemAnimator) rvPhoto.getItemAnimator()).setSupportsChangeAnimations(false);
    }

    private void initData() {
        chooseFilePop = new ChooseFilePop(cacheNameCode, context.get(), flMenu);
        graphUtils = new GraphUtils();
        getData();
    }

    private void initListener() {
        tvFile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (chooseFilePop != null)
                    if (chooseFilePop.isShowing()) chooseFilePop.dismiss();
                    else chooseFilePop.show(event);
            }
        });

        rvPhoto.addOnChildAttachStateChangeListener(new RecyclerView.OnChildAttachStateChangeListener() {
            @Override
            public void onChildViewAttachedToWindow(View view) {
                if (view instanceof PhotoSelectedView) {
                    PhotoSelectedView psv = (PhotoSelectedView) view;
                    if (psv != null) {
                        psv.setImg(cacheNameCode, psv.getIndex(), psv.getUri());
                    }
                }
            }

            @Override
            public void onChildViewDetachedFromWindow(View view) {
                if (view instanceof PhotoSelectedView) {
                    PhotoSelectedView psv = (PhotoSelectedView) view;
                    if (psv != null) {
                        psv.clearImg();
                    }
                }
            }
        });
        ivLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onFinish()) finish();
            }
        });

        tvRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (view.getTag() != null && (boolean) view.getTag()) {
                    isSaveChooseWhenExit = true;
                    saveAndFinish();
                } else {
                    ToastUtils.show(getApplicationContext(), "请至少选择一张图片");
                }
            }
        });
        tvPreview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (view.getTag() != null && (boolean) view.getTag()) {
                    startPreviewActivity(true, false, PhotographHelper.getHelper().getCurSelectedPhotos(cacheNameCode).get(0).uri);
                } else {
                    ToastUtils.show(getApplicationContext(), "请至少选择一张图片");
                }
            }
        });
        event = new PhotoEvent() {
            @Override
            public void onEvent(int code, boolean isValidate) {
                /**
                 * 相册数据获取并同步完成，可直接使用
                 * */
                if (isValidate)
                    switch (code) {
                        case helperEvenErroCode:
                            ToastUtils.show(getApplicationContext(), "暂时还没有图片喔！");
                            break;
                        case helperEventCode:
                            hasEventData = true;
                            setData();
                            break;
                        case helperEventCode_SelectedChange:
                            setDisplayView();
                            break;
                        default:
                            break;
                    }
            }
        };
    }

    /**
     * 设置显示方式，预览／完成等
     */
    private void setDisplayView() {
        int size = PhotographHelper.getHelper().curSelectedSize(cacheNameCode);
        tvRight.setText(" 完成" + (size <= 0 ? "" : "(" + size + "/" + maxPhotoSize + ") "));
        tvRight.setTextColor(Color.WHITE);
        tvRight.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
        tvRight.setBackground(ContextCompat.getDrawable(context.get(), R.drawable.photo_compile_green));
        int padding_lr = DisplayUtils.dip2px(getApplicationContext(), 8);
        int padding_td = DisplayUtils.dip2px(getApplicationContext(), 4);
        tvRight.setPadding(padding_lr, padding_td, padding_lr, padding_td);
        tvPreview.setText("预览" + (size <= 0 ? "" : "(" + size + ")"));
        tvPreview.setTag(size > 0);
        tvRight.setTag(size > 0);
    }

    /**
     * 设置图片数据
     */
    private void setData() {
        hasEventData = false;
        List<PhotoInfo> infos = PhotographHelper.getHelper().getAllPhotos();
        if (infos == null || infos.size() <= 0) return;
        setDisplayView();
        adapter.clear();
        adapter.add(infos);
//        hint(BaseLoadingView.DisplayMode.normal, "", false);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (hasEventData)
            setData();
        else {
            setDisplayView();
            adapter.notifyDataSetChanged();
        }
    }

    private void saveAndFinish() {
        if (isSaveChooseWhenExit) PhotographHelper.getHelper().saveSelectedPhotos(cacheNameCode);
        isSaveChooseWhenExit = false;
        finish();
    }

    @Override
    public void finish() {
        super.finish();
    }

    @Override
    protected void onDestroy() {
        synchronized (this) {
            PhotographHelper.getHelper().clearSelectedCache();
            PhotoFileHelper.getInstance("").release();
            if (chooseFilePop != null) {
                chooseFilePop.release();
                chooseFilePop = null;
            }
            rvPhoto.removeAllViews();
            rvPhoto = null;
            adapter.release();
            adapter.clear();
            adapter = null;
            graphUtils.onDestory();
            graphUtils = null;
            event = null;
            context.clear();
            context = null;
            super.onDestroy();
        }
    }

    /**
     * 异步取所有本地图片
     */
    private void getData() {
        graphUtils.getImgData(this, new GraphUtils.GetImgData() {
            @Override
            public void onGetParent(List<PhotoFileInfo> infos) {
                PhotoFileHelper.getInstance(cacheNameCode).setFileInfos(infos, event);
            }

            @Override
            public void onFail() {
                if (adapter.getCount() > 0) adapter.clear();
//                hint(BaseLoadingView.DisplayMode.noData, "相册读取失败", false);
            }
        });
    }

    private void startPreviewActivity(boolean isSelected, boolean isAll, String uri) {
        Intent intent = new Intent(context.get(), PhotoPreviewActivity.class);
        intent.putExtra("curImgUri", uri);
        intent.putExtra("cacheNameCode", cacheNameCode);
        intent.putExtra("isSelected", isSelected);
        intent.putExtra("maxPhotoSize", maxPhotoSize);
        intent.putExtra("isAll", isAll);
        startActivityForResult(intent, Constancs.REQUST_OPEN_PREVIEW);
    }

    private boolean onFinish() {
        if (chooseFilePop != null && chooseFilePop.isShowing()) {
            chooseFilePop.dismiss();
            return false;
        }
        return true;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (onFinish()) {
                return super.onKeyDown(keyCode, event);
            }
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constancs.REQUST_OPEN_PREVIEW && resultCode == Constancs.RESULT_COMPLETED) {
            isSaveChooseWhenExit = true;
            saveAndFinish();
        }
    }
}
